/*******************************************************************************
 * Copyright (c) 2013 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
/**
 * 
 */
package com.niannian.activity;

import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.SharedPreferences.Editor;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.niannian.adapter.ListDialogAdapter;
import com.niannian.adapter.MyFamilyMemberAdaper;
import com.niannian.bean.MyFamilyMemberBean;
import com.niannian.dialog.SimpleListDialog;
import com.niannian.dialog.SimpleListDialog.onSimpleListItemClickListener;
import com.niannian.dialog.YesNoDialog2;
import com.niannian.dialog.YesNoDialog2.onSimpleOnCancelListener;
import com.niannian.dialog.YesNoDialog2.onSimpleOnClicklListener;
import com.niannian.util.AsyncHandle;
import com.niannian.util.Common;
import com.niannian.util.ErrorCode;
import com.niannian.util.MyTextWatcher;
import com.niannian.util.UmengPage;
import com.niannian.web.nnSyncApi;
import com.niannian.BaseActivity;
import com.niannian.R;
import com.umeng.analytics.MobclickAgent;

/**
 * 家庭成员列表
 * 
 * @author shengl
 * 
 */
public class MyFamilyMemberActivity extends BaseActivity {
	LinearLayout ll_add_member_phone;
	EditText reg_member_phone;
	Button btn_member_add;

	RelativeLayout rl_add_family_member;
	TextView tv_add_family_member_tip;
	private ListView my_family_member_list;
	private MyFamilyMemberAdaper myFAdaper;
	public static final int MEMBER_DETAIL = 1;

	private int ACTION_TYPE = 0;// 0表示查看家庭成员，1表示邀请家庭成员
	private String[] item;

	String phone = "";
	String name = "";

	private Activity mActivity;
	private static final int REQUEST_CONTACT = 10;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

		setContentView(R.layout.activity_family_member);
		addActToGroup("All", this);
		initData();
		initView();
		setLister();
		initTopView();
		updata();
		new GetMyFamilyMenber().init(MyFamilyMemberActivity.this, null, false, "").execute();
		mActivity = this;
	}

	private void initData() {
		try {
			ACTION_TYPE = getIntent().getIntExtra("ACTION_TYPE", 0);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	// 头部视图
	private ImageView iv_top_left, iv_top_right;
	private TextView top_title;
	private LinearLayout iv_top_left2, top_title2;

	private void initTopView() {
		iv_top_left = (ImageView) findViewById(R.id.iv_top_left);
		iv_top_left2 = (LinearLayout) findViewById(R.id.iv_top_left2);
		iv_top_left.setVisibility(View.VISIBLE);
		iv_top_left2.setVisibility(View.GONE);

		top_title = (TextView) findViewById(R.id.top_title);
		top_title2 = (LinearLayout) findViewById(R.id.top_title2);
		top_title.setVisibility(View.VISIBLE);
		top_title2.setVisibility(View.GONE);

		iv_top_right = (ImageView) findViewById(R.id.iv_top_right);
		iv_top_right.setImageResource(R.drawable.fm);
		iv_top_left.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myfinish();
			}
		});
		if (ACTION_TYPE == 0) {

			iv_top_right.setVisibility(View.VISIBLE);
			top_title.setText("亲友");
		} else {

			iv_top_right.setVisibility(View.GONE);
			top_title.setText("选择联系人");
			tv_add_family_member_tip.setText("手机通讯录");
		}
		iv_top_right.setOnClickListener(new OnClickListener() { 
			@Override
			public void onClick(View v) {
				// openActivity(AddFamilyMemberActivity.class);
				// startAnimationLeftToRight();
				initPopuwindow();
			}
		});
	}

	private void initView() {
		ll_add_member_phone = (LinearLayout) findViewById(R.id.ll_add_member_phone);
		reg_member_phone = (EditText) findViewById(R.id.reg_member_phone);
		reg_member_phone.addTextChangedListener(textWatcher);
		btn_member_add = (Button) findViewById(R.id.btn_member_add);
		
		rl_add_family_member = (RelativeLayout) findViewById(R.id.rl_add_family_member);
		tv_add_family_member_tip = (TextView) findViewById(R.id.tv_add_family_member_tip);
		
		my_family_member_list = (ListView) findViewById(R.id.my_family_member_list);
		myFAdaper = new MyFamilyMemberAdaper(MyFamilyMemberActivity.this, ACTION_TYPE);
		my_family_member_list.setAdapter(myFAdaper);

		if (ACTION_TYPE == 0) {
			if (userInfoManager.family_perm == 1) {
				rl_add_family_member.setVisibility(View.VISIBLE);
				ll_add_member_phone.setVisibility(View.VISIBLE);
				SharedPreferences sp = getSharedPreferences("guidance", Context.MODE_PRIVATE);
				boolean first = sp.getBoolean("firstGuidance5", true);
				if (first) {
				
					Editor edit = sp.edit();
					edit.putBoolean("firstGuidance5", false);
					edit.commit();
				} else {
					
				}

			} else {
				ll_add_member_phone.setVisibility(View.GONE);
				rl_add_family_member.setVisibility(View.GONE);
				
			}
		} else {
			ll_add_member_phone.setVisibility(View.GONE);
			rl_add_family_member.setVisibility(View.VISIBLE);
			
		}
	}

	private void setLister() {
		rl_add_family_member.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				MobclickAgent.onEvent(mActivity, UmengPage.ADD_FRIEND_FROM_CONTACTS);
				// MobclickAgent.onEvent(mActivity, "click", "button");
				requetContact();
			}
		});
		
		btn_member_add.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				name = "";
				phone = reg_member_phone.getText().toString().trim();
				if (phone.length() != 11) {
					Common.tip(MyFamilyMemberActivity.this, "请输入您的11位手机帐号");
					return;
				}
				new GetSmsContent().init(MyFamilyMemberActivity.this, null, true, "请稍等...").execute();
			}
		});
	}

	private MyTextWatcher textWatcher = new MyTextWatcher() {

		@Override
		public void onFocusChange(View view, boolean hasFocus) {
		};

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			String acct = reg_member_phone.getText().toString().trim();
			if (!Common.empty(acct)) {
				btn_member_add.setEnabled(true);
			} else {
				btn_member_add.setEnabled(false);
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK) {
			return;
		}

		switch (requestCode) {
		case MEMBER_DETAIL:
			final Bundle b = data.getExtras();
			MyFamilyMemberBean fdata = (MyFamilyMemberBean) b.get("rdata");
			myFAdaper.getFDatasList().set(b.getInt("position"), fdata);
			myFAdaper.notifyDataSetChanged();
			break;
		case REQUEST_CONTACT:
			if (data == null) { // Toast.makeText(getApplicationContext(),
								// "你没有选择联系人", Toast.LENGTH_LONG).show();
			} else {
				phone = "";
				name = "";
				Uri contactURI = data.getData();
				Cursor cursor = getContentResolver().query(contactURI, null, null, null, null);
				while (cursor.moveToNext()) {
					StringBuilder sb = new StringBuilder();
					// 获取联系人的ID
					String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

					// 获取联系人的姓名
					name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
					String pString = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
					if (Integer.parseInt(pString) == 0) {
						Common.tip(MyFamilyMemberActivity.this, "手机号格式错误");
					} else {
						try {
							Cursor phoneCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
									ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
							item = new String[phoneCursor.getCount()];
							int i = 0;
							while (phoneCursor.moveToNext()) {
								phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
								phone = phone.replaceAll(" ", "");
								phone = phone.replaceAll("-", "");
								item[i] = phone;
								i++;
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
						try {
							if (Common.empty(item)) {
								phone = contactURI.toString().split("lookup")[1].split("/")[1].split("i")[1].substring(0, 11);
								if (ACTION_TYPE == 0) {
									new GetSmsContent().init(MyFamilyMemberActivity.this, null, true, "请稍等...").execute();
								} else {
									fromBook();
								}
							} else {
								if (item.length > 1) {
									initListDialog();
								} else {
									if (ACTION_TYPE == 0) {
										new GetSmsContent().init(MyFamilyMemberActivity.this, null, true, "请稍等...").execute();
									} else {
										fromBook();
									}
								}
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
					}

				}
			}
			break;

		default:
			break;
		}
	}

	protected class GetMyFamilyMenber extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			// Common.tip(MyFamilyMemberActivity.this, "获取失败");
		}

		protected void handleData(JSONObject json, Map<String, Object> paramMap) throws JSONException {
			try {
				int retCode = json.getInt("code");
				if (retCode == ErrorCode.OK) {
					// Common.tip(MyFamilyMemberActivity.this, "获取成功");
					myFAdaper.getFDatasList().clear();
					databaseapi.updateMyFamily(userInfoManager.id, json.getJSONArray("data"));
					updata();

				} else {
					// Common.tip(MyFamilyMemberActivity.this,
					// ErrorCode.GetErrorMsg(retCode));
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		protected String runTask(Map<String, Object> paramMap) {
			return nnSyncApi.getFamilyMember();
		}
	}

	private void updata() {
		try {
			List<MyFamilyMemberBean> list = databaseapi.loadMyFamily(userInfoManager.id);
			if (ACTION_TYPE == 1) {
				for (int i = 0; i < list.size(); i++) {
					if (list.get(i).getId() == userInfoManager.id) {
						list.remove(i);
						break;
					}
				}
			}
			myFAdaper.getFDatasList().addAll(list);
			myFAdaper.notifyDataSetChanged();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public void requetContact() {
		Intent contactIntent = new Intent();
		contactIntent.setAction(Intent.ACTION_PICK);
		contactIntent.setType(ContactsContract.Contacts.CONTENT_TYPE);
		startActivityForResult(contactIntent, REQUEST_CONTACT);
	}

	public void sendSMS(String phone, String smsData) {

		/*
		 * SmsManager smsManager = SmsManager.getDefault(); List<String>
		 * divideContents = smsManager.divideMessage(smsData); for (String text
		 * : divideContents) { smsManager.sendTextMessage(phone, null, text,
		 * null, null); }
		 */

		Uri uri = Uri.parse("smsto:" + phone);
		Intent it = new Intent(Intent.ACTION_SENDTO, uri);
		it.putExtra("sms_body", smsData);
		startActivity(it);
	}

	String sms_content = "";

	protected class GetSmsContent extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(MyFamilyMemberActivity.this, "操作失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			try {
				int retCode = paramJSONObject.getInt("code");
				if (retCode == ErrorCode.OK) {

					sms_content = paramJSONObject.getString("sms_content");

					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = paramJSONObject.getJSONObject("data");
					jsonArray.put(jsonObject);

					databaseapi.updateMyFamily(userInfoManager.id, jsonObject);

					int gid = jsonObject.getInt("id");

					MyFamilyMemberBean data = databaseapi.loadOneMyFamily(userInfoManager.id, gid);
					if (!Common.empty(data)) {
						myFAdaper.getFDatasList().add(0, data);
						myFAdaper.notifyDataSetChanged();
					}

					initDialog3();

					// sendSMS(phone, sms_content);
				} else {
					Common.tip(mActivity, paramJSONObject.getString("msg"));
				}
			} catch (Exception e) {

			}
		}

		protected String runTask(Map<String, Object> paramMap) {
			return nnSyncApi.addFamilyMember(phone, name);
		}
	}

	PopupWindow RightPopupWindow;
	Button bt_delete_family;

	@SuppressWarnings("deprecation")
	private void initPopuwindow() {
		View mMenuView = null;

		if (RightPopupWindow == null) {
			mMenuView = LayoutInflater.from(MyFamilyMemberActivity.this).inflate(R.layout.member_choose_popupwindow, null);
			bt_delete_family = (Button) mMenuView.findViewById(R.id.bt_delete_family);
			bt_delete_family.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					initDialog();
					RightPopupWindow.dismiss();
				}
			});

			RightPopupWindow = new PopupWindow(mMenuView, mScreenWidth / 2 + 60, LayoutParams.WRAP_CONTENT, true);
			RightPopupWindow.setBackgroundDrawable(new BitmapDrawable());
			RightPopupWindow.setOutsideTouchable(true);
			RightPopupWindow.setAnimationStyle(R.style.Popup_Animation_DownScale);
		} else {
			mMenuView = RightPopupWindow.getContentView();
		}

		if (userInfoManager.family_perm == 1) {
			bt_delete_family.setText("解散家庭");

			if (myFAdaper.getFDatasList().size() <= 1) {
				bt_delete_family.setEnabled(true);
				bt_delete_family.setTextColor(getResources().getColor(R.color.col_c));
			} else {
				bt_delete_family.setEnabled(false);
				bt_delete_family.setTextColor(getResources().getColor(R.color.col_b));
			}

		} else {
			bt_delete_family.setText("退出家庭");
			bt_delete_family.setEnabled(true);
		}

		RightPopupWindow.showAsDropDown(iv_top_right, -0, -0);
	}

	YesNoDialog2 tip;

	private void initDialog() {
		if (userInfoManager.family_perm == 1) {
			tip = new YesNoDialog2(mActivity, "确认解散家庭?");
			tip.setMsg2("解散后, 家庭内部所有图片和语音数据将丢失, 请慎重.");
		} else {
			tip = new YesNoDialog2(mActivity, "确认退出家庭？");
			tip.setMsg2("注意: 退出家庭后, 您将无法再与家庭成员互动. 如需再次进入家庭, 请与家庭管理员联系.");
		}

		tip.setcancelButtonText("取  消");
		tip.setConfimButtonText("确  定");
		tip.setOnCancelListener(new onSimpleOnCancelListener() {

			@Override
			public void onCancel() {
				tip.dismiss();
			}
		});
		tip.setOnConfimClickListener(new onSimpleOnClicklListener() {

			@Override
			public void onClick() {

				new FamilyMenmber().init(mActivity, null, true, "请求中...").execute();
				tip.dismiss();
			}
		});
		tip.show();
	}

	protected class FamilyMenmber extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(mActivity, "操作失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			int retCode = paramJSONObject.getInt("code");
			if (retCode == ErrorCode.OK) {
				try {
					Common.tip(mActivity, "操作成功");
					destroyGroup("All");
					userInfoManager.family = 0;
					update_gUser();
					openActivity(CreateFamilyActivity.class);
					myfinish();

					return;
				} catch (Exception e) {
					// TODO: handle exception
				}
			} else {
				Common.tip(mActivity, paramJSONObject.getString("msg"));
			}
		}

		protected String runTask(Map<String, Object> paramMap) {
			if (userInfoManager.family_perm == 1) {
				return nnSyncApi.deleteFamily();
			} else {
				return nnSyncApi.deleteFamilyMenber(userInfoManager.id, 0);
			}
		}
	}

	YesNoDialog2 tip3;

	private void initDialog3() {

		tip3 = new YesNoDialog2(mActivity, "您已成功添加  " + ("".equals(name) ? phone : name) + "  为家庭成员. 记得发送短信告诉Ta, 以便Ta能正常访问家庭与您互动");

		tip3.setHideCancel();
		tip3.setConfimButtonText("确  定");

		tip3.setOnConfimClickListener(new onSimpleOnClicklListener() {

			@Override
			public void onClick() {
				tip3.dismiss();

			}
		});
		tip3.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				// TODO Auto-generated method stub
				sendSMS(phone, sms_content);
				Common.tip(MyFamilyMemberActivity.this, "操作成功");
			}
		});
		tip3.show();
	}

	SimpleListDialog listDialog;

	private void initListDialog() {
		listDialog = new SimpleListDialog(mActivity);
		listDialog.setAdapter(new ListDialogAdapter(mActivity, item));

		listDialog.serOnSimpleListItemClikListener(new onSimpleListItemClickListener() {
			@Override
			public void onItemClick(int postion) {

				listDialog.dismiss();
				phone = item[postion];
				if (ACTION_TYPE == 0) {
					new GetSmsContent().init(MyFamilyMemberActivity.this, null, true, "请稍等...").execute();
				} else {
					fromBook();
				}

			}
		});
		listDialog.show();
	}

	private void fromBook() {
		Intent intent = new Intent();
		int from = 2;// 表示来自通讯录
		intent.putExtra("from", from);
		intent.putExtra("phone", phone);
		intent.putExtra("name", name);
		setResult(RESULT_OK, intent);
		myfinish();
	}
}
